using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using PrimitiveEngine;
using PrimitiveEngine.Primitives;
using FrameRateCounterComponent;
using SpriteRenderEngine;

namespace PrimitiveEngineTest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class PrimitiveEngineTest : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        RenderTarget2D[] renderTarget2D = new RenderTarget2D[2];
        DepthStencilBuffer depthStencil;
        PrimitiveBatch primitiveBatch;
        SpriteFont font;
        List<PELine> lines;
        List<PECircle> circles;
        List<PERectangle> rects;
        List<PEEllipse> ellipses;

        // graphs
        GraphRenderHelper timeGraph;


        public PrimitiveEngineTest()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 1024;
            graphics.SynchronizeWithVerticalRetrace = false;
            IsFixedTimeStep = false;
            TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16);

            FrameRateCounter fps = new FrameRateCounter(this);
            Components.Add(fps);

            graphics.PreferMultiSampling = true;
            graphics.PreparingDeviceSettings +=
              new EventHandler<PreparingDeviceSettingsEventArgs>(
                  graphics_PreparingDeviceSettings);

        }

        #region AA
        void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
        {
            // Xbox 360 and most PCs support FourSamples/0 
            // (4x) and TwoSamples/0 (2x) antialiasing.
            PresentationParameters pp =
                e.GraphicsDeviceInformation.PresentationParameters;
#if XBOX
            pp.MultiSampleQuality = 0;
            pp.MultiSampleType = MultiSampleType.FourSamples;
            return;
#else
            int quality = 0;
            GraphicsAdapter adapter = e.GraphicsDeviceInformation.Adapter;
            SurfaceFormat format = adapter.CurrentDisplayMode.Format;
            // Check for 4xAA
            if (adapter.CheckDeviceMultiSampleType(DeviceType.Hardware, format,
                false, MultiSampleType.FourSamples, out quality))
            {
                // even if a greater quality is returned, we only want quality 0
                pp.MultiSampleQuality = 0;
                pp.MultiSampleType =
                    MultiSampleType.FourSamples;
            }
            // Check for 2xAA*/
            if (adapter.CheckDeviceMultiSampleType(DeviceType.Hardware,
                format, false, MultiSampleType.TwoSamples, out quality))
            {
                // even if a greater quality is returned, we only want quality 0
                pp.MultiSampleQuality = 0;
                pp.MultiSampleType =
                    MultiSampleType.FourSamples;
            }
            return;
#endif
        }
        #endregion

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            lines = new List<PELine>();
            circles = new List<PECircle>();
            rects = new List<PERectangle>();
            ellipses = new List<PEEllipse>();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            Random r = new Random();
            Color c;

            for (int i = 0; i < 30; i++)
            {
                c = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble() + 0.5f);
                rects.Add(new PERectangle(r.Next(10, 100), r.Next(10, 100), (float)r.NextDouble(), c));
                rects[i].Position = new Vector2(r.Next(-450, 450), r.Next(-450, 450));
                rects[i].Rotation = (float)r.NextDouble() * 6.28f;
                rects[i].BorderWidth = r.Next(2, 8);

                c = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble() + 0.5f);
                circles.Add(new PECircle(new Vector2(r.Next(-450, 450), r.Next(-450, 450)), r.Next(30, 100), (float)r.NextDouble(), c));
                circles[i].BorderWidth = r.Next(2, 8);

                c = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble() + 0.5f);
                ellipses.Add(new PEEllipse(new Vector2(r.Next(-450, 450), r.Next(-450, 450)), r.Next(10, 100), r.Next(10, 100), (float)r.NextDouble(), c));
                ellipses[i].BorderWidth = r.Next(2, 8);
                ellipses[i].Rotation = (float)r.NextDouble() * 6.28f;

                c = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble() + 0.5f);

                lines.Add(new PELine(new Vector2(r.Next(-450, 450), r.Next(-450, 450)), new Vector2(r.Next(-450, 450), r.Next(-450, 450)), (float)r.NextDouble(), c));
                lines[i].BorderWidth = r.Next(1, 3);
                lines[i].Width = r.Next(10, 15);
            }

            
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            primitiveBatch = new PrimitiveBatch(GraphicsDevice);

            timeGraph = new GraphRenderHelper(GraphicsDevice, 500, 0f, 5f, Color.Blue);
            timeGraph.AutoScale = false;
            
            
            renderTarget2D[0] = new RenderTarget2D(graphics.GraphicsDevice, graphics.PreferredBackBufferWidth , graphics.PreferredBackBufferHeight , 1,
                graphics.GraphicsDevice.DisplayMode.Format, GraphicsDevice.PresentationParameters.MultiSampleType, 0);
            renderTarget2D[1] = new RenderTarget2D(graphics.GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, 1,
                graphics.GraphicsDevice.DisplayMode.Format, GraphicsDevice.PresentationParameters.MultiSampleType, 0);
            

            depthStencil = CreateDepthStencil(renderTarget2D[0]);

            font = Content.Load<SpriteFont>("System");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            

            base.Update(gameTime);
        }
        
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            MouseState m = Mouse.GetState();

            graphics.GraphicsDevice.Clear(Color.LightGray);

            //GraphicsDevice.RenderState.FillMode = FillMode.WireFrame;


            primitiveBatch.Begin(Matrix.CreateOrthographic(1024, 1024, 0, 1), Matrix.CreateRotationZ((float)gameTime.TotalGameTime.TotalSeconds * 0.1f) *
                Matrix.CreateTranslation((float)Math.Sin(gameTime.TotalGameTime.TotalSeconds) * 200f, (float)Math.Cos(gameTime.TotalGameTime.TotalSeconds) * -200f, 0));

            foreach (var item in lines)
            {
                primitiveBatch.DrawLine(item);
            }

            foreach (var item in circles)
            {
                primitiveBatch.DrawCircle(item);
            }

            foreach (var item in ellipses)
            {
                primitiveBatch.DrawEllipse(item);
            }

            foreach (var item in rects)
            {
                primitiveBatch.DrawRectangle(item);
            }

            List<Vector2> points = new List<Vector2>();

            points.Add(new Vector2(-100, 60));
            points.Add(new Vector2(0, 600));
            points.Add(new Vector2(100, 60));
            points.Add(new Vector2(60, -100));
            points.Add(new Vector2(-60, -100));

            PEPolygon poly = new PEPolygon(points);
            poly.Position = new Vector2((float)Math.Sin(gameTime.TotalGameTime.TotalSeconds * 2f) * -200f, 0);
            poly.Rotation = (float)gameTime.TotalGameTime.TotalSeconds;
            poly.IsFilled = true;
            poly.FillColor = new Color(0f, 0f, 1f, 0.8f);
            poly.BorderColor = new Color(0f, 0f, 0f, 1f);
            poly.Layer = 0;
            poly.BorderWidth = 3;

            primitiveBatch.DrawPolygon(poly);

            primitiveBatch.End();

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);

            spriteBatch.DrawString(font, "Per Frame-", new Vector2(10, 10), Color.White);
            spriteBatch.DrawString(font, "Total Triangles: " + primitiveBatch.TriangleCount.ToString(), new Vector2(10, 30), Color.White);
            spriteBatch.DrawString(font, "Total Vertices: " + primitiveBatch.VertexCount.ToString(), new Vector2(10, 50), Color.White);
            spriteBatch.DrawString(font, "Total Draw Calls: " + primitiveBatch.DrawCalls.ToString(), new Vector2(10, 70), Color.White);
            spriteBatch.DrawString(font, "Total Opaque Primitives: " + primitiveBatch.OpaquePrimitiveCount.ToString(), new Vector2(10, 90), Color.White);
            spriteBatch.DrawString(font, "Total Transparent Primitives: " + primitiveBatch.TransparentPrimitiveCount.ToString(), new Vector2(10, 110), Color.White);
            spriteBatch.DrawString(font, "Time in Milliseconds: " + primitiveBatch.RenderTime.TotalMilliseconds.ToString(), new Vector2(10, 130), Color.White);

            spriteBatch.End();

            timeGraph.UpdateGraph((float)primitiveBatch.RenderTime.TotalMilliseconds);
            timeGraph.Render(new Rectangle(graphics.PreferredBackBufferWidth - 300, 0, 300, 100));

            base.Draw(gameTime);
        }

        public static DepthStencilBuffer CreateDepthStencil(
            RenderTarget2D target)
        {
            return new DepthStencilBuffer(target.GraphicsDevice, target.Width,
                target.Height, target.GraphicsDevice.DepthStencilBuffer.Format,
                target.MultiSampleType, target.MultiSampleQuality);
        }

        public static DepthStencilBuffer CreateDepthStencil(
            RenderTarget2D target, DepthFormat depth)
        {
            if (GraphicsAdapter.DefaultAdapter.CheckDepthStencilMatch(
                DeviceType.Hardware,
                GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Format,
                target.Format,
                depth))
            {
                return new DepthStencilBuffer(target.GraphicsDevice,
                    target.Width, target.Height, depth,
                    target.MultiSampleType, target.MultiSampleQuality);
            }
            else
                return CreateDepthStencil(target);
        }
    }
}
